/*
 * SearcherServer.java
 *
 * Created on 28 luglio 2005, 12.19
 * @version 1.1
 * @author Federico Paparoni
 *
*/

package com.javastaff.btfree;
import javax.bluetooth.*;
import java.util.*;
import javax.microedition.io.*;

public class SearcherServer {
    
    private LocalDevice localDevice;
    private DiscoveryAgent agent;
    private Searcher searcher;
    private UUID uuid ;
    private StreamConnection conn=null;
    private Receiver et;
    
    public SearcherServer(Receiver et,String uuid,String nome) {
        this.et=et;
        this.uuid=new UUID(uuid, false);
        searcher=new Searcher(this, nome);
        try {
            localDevice = LocalDevice.getLocalDevice();
            agent = localDevice.getDiscoveryAgent();
            agent.startInquiry(DiscoveryAgent.GIAC,searcher);
        }
        catch(Exception e){
        }
    }
    
    public void devicesFound(Vector devicesFound) {
        int[] attrSet = {0x0100};
        UUID[] uuidSet = new UUID[1];
        uuidSet[0] = uuid;
        
        
        try {
            for (int i=0;i<devicesFound.size();i++)
                agent.searchServices(attrSet, uuidSet, (RemoteDevice)devicesFound.elementAt(i), searcher);
        } catch(Exception e) {
        }
    }
    
    public void servicesFound(ServiceRecord serviceRecord) {
        String url = serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
        try{
            conn = (StreamConnection)Connector.open(url);
            et.connectionEstablished();
        }
        catch(Exception e){
        }
    }
    
    public StreamConnection getConnection() {
        return conn;
    }
    
}
